package com.example.keli.ui.userinfo;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.keli.R;
import com.example.keli.api.HttpUtils;
import com.example.keli.api.RetrofitManager;
import com.example.keli.api.http.api.BaseResponse;
import com.example.keli.api.http.api.subscriber.SubscriberListener;
import com.example.keli.base.App;
import com.example.keli.base.BaseActivity;
import com.example.keli.base.app.C;
import com.example.keli.base.utils.AlbumUtil;
import com.example.keli.base.utils.GlideUtil;
import com.example.keli.base.utils.LogUtils;
import com.example.keli.base.utils.RxCallBack;
import com.example.keli.base.utils.RxThreadUtils;
import com.example.keli.base.utils.TimeUtils;
import com.example.keli.base.utils.ToastUtil;
import com.example.keli.ui.my.model.UserInfo;
import com.flyco.roundview.RoundTextView;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.AlbumFile;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * description: 个人资料
 * author: Allen
 * date: 2019/3/25 15:13
 */
public class PersonDataActivity extends BaseActivity {

    @BindView(R.id.avatar)
    ImageView avatar;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.birthday)
    TextView birthday;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.job)
    TextView job;
    @BindView(R.id.education)
    TextView education;
    @BindView(R.id.height)
    EditText height;
    @BindView(R.id.weight)
    EditText weight;
    @BindView(R.id.flowlayout)
    TagFlowLayout flowlayout;
    @BindView(R.id.sign)
    EditText sign;
    @BindView(R.id.save)
    RoundTextView save;
    @BindView(R.id.nick_name)
    EditText nickName;

    List<String> hobbyList = new ArrayList<>();
    TagAdapter tagAdapter;
    @BindView(R.id.wechat_code)
    EditText wechatCode;

    public static void start(Context context) {
        Intent intent = new Intent(context, PersonDataActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_person_data;
    }

    @Override
    protected void bindData() {
        abTitle.setText("个人资料");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        hobbyList.add("  +  ");
        tagAdapter = new TagAdapter(hobbyList) {
            @Override
            public View getView(FlowLayout parent, int position, Object o) {
                View view = getLayoutInflater().inflate(R.layout.item_hobby_tag, parent, false);
                RoundTextView roundTextView = view.findViewById(R.id.roundtext);
                roundTextView.setText(hobbyList.get(position));
                return view;
            }

            @Override
            public void onSelected(int position, View view) {
                super.onSelected(position, view);
                if (position == 0) {
                    SelectHobbyActivity.start(PersonDataActivity.this, hobby_ids);
                }
            }

            @Override
            public void unSelected(int position, View view) {
                super.unSelected(position, view);
            }

            @Override
            public boolean setSelected(int position, Object o) {
                return super.setSelected(position, o);
            }
        };
        flowlayout.setAdapter(tagAdapter);
//        tagAdapter.notifyDataChanged();

        getUserInfo();
    }

    @OnClick({R.id.sex, R.id.phone, R.id.birthday, R.id.address, R.id.job, R.id.education, R.id.save, R.id.avatar_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sex:
                selectSome(R.array.sex_list, 1,sex.getText().toString());
                break;
            case R.id.phone:
                break;
            case R.id.birthday:
                showCalendar();
                break;
            case R.id.address:
                Intent intent = new Intent(PersonDataActivity.this, SelectAddressActivity.class);
                startActivityForResult(intent, 1000);
                break;
            case R.id.job:
                selectSome(R.array.job_list, 2,job.getText().toString());
                break;
            case R.id.education:
                selectSome(R.array.education_list, 3,education.getText().toString());
                break;
            case R.id.save:
                if (TextUtils.isEmpty(avatar_url)) {
                    ToastUtil.show("请上传头像");
                    return;
                }
                if (nickName.getText().toString().length() < 2) {
                    ToastUtil.show("昵称最少两个字符");
                    return;
                }
                if(!TextUtils.isEmpty(height.getText().toString())){
                    if (Double.valueOf(height.getText().toString()) < 100||Double.valueOf(height.getText().toString()) > 220) {
                        ToastUtil.show("身高不能小于100或大于220");
                        return;
                    }
                }
                if(TextUtils.isEmpty(sex_p)){
                    ToastUtil.show("请选择性别");
                    return;
                }
                if(TextUtils.isEmpty(region_id)){
                    ToastUtil.show("请选择参赛地区");
                    return;
                }
//                if(!TextUtils.isEmpty(weight.getText().toString())){
//                    if (Double.valueOf(weight.getText().toString()) < 40||Double.valueOf(weight.getText().toString()) > 100) {
//                        ToastUtil.show("体重不能小于40或大于100");
//                        return;
//                    }
//                }
                setUserInfo();
                break;
            case R.id.avatar_layout:
                AlbumUtil.getImages(PersonDataActivity.this, 1, new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
                        if (result.size() > 0) {
                            uptokens(result.get(0).getPath());
                        }
                    }
                });
                break;
        }
    }

    private void uptokens(final String path) {
        RetrofitManager.ApiFunc(RetrofitManager.mApiFunc.uptokens(), new SubscriberListener<BaseResponse<String>>() {
            @Override
            public void onSuccess(BaseResponse<String> response) {
                                Configuration config = new Configuration.Builder()
                                        .dns(null)
                                        .build();
                                String key = String.valueOf(System.currentTimeMillis());
                                UploadManager uploadManager = new UploadManager(config);
                                uploadManager.put(path, key, response.getData(),
                                        new UpCompletionHandler() {

                            @Override
                            public void complete(String key, ResponseInfo info, JSONObject res) {
                                //res包含hash、key等信息，具体字段取决于上传策略的设置
                                if (info.isOK()) {
                                    LogUtils.loge("qiniu", "Upload Success");
                                    avatar_url = C.Constance.IMAGE_HOST + key + "?imageslim";
                                    GlideUtil.displayCircle(PersonDataActivity.this, avatar, avatar_url);
                                } else {
                                    LogUtils.loge("qiniu", "Upload Fail");
                                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                                }
                            }
                        }, null);
            }

            @Override
            public void onFailer(String msg) {
            }

            @Override
            public void onTokenError() {
            }
        });
    }

    private void showCalendar() {
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(PersonDataActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                birthday.setText(TimeUtils.getYearMonthDay(date));
            }
        }).setType(new boolean[]{true, true, true, false, false, false}).setRangDate(null, Calendar.getInstance()).build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1001) {
            LogUtils.loge("地址>>>" + data.getStringExtra("label"));
            LogUtils.loge("pid是多少》》》" + data.getStringExtra("pid"));
            address.setText(data.getStringExtra("label"));
            region_id = data.getStringExtra("pid");
        } else if (resultCode == 1003) {
            hobby_ids = data.getStringExtra("hobby");
            LogUtils.loge(hobby_ids);
            String[] hobbyString = hobby_ids.split(",");
            hobbyList.clear();
            hobbyList.add("  +  ");
            hobbyList.addAll(Arrays.asList(hobbyString));
            tagAdapter.notifyDataChanged();
        }
    }

    private void selectSome(int arrays, final int flag,String text) {
        List<String> stringB = Arrays.asList(getResources().getStringArray(arrays));
        int position = -1;
        for (int i = 0; i < stringB.size(); i++) {
            if(TextUtils.equals(text,stringB.get(i))){
                position = i;
            }
        }
        if(flag==1&&position == -1){
            //默认是女
            position = 0;
        }
        new MaterialDialog.Builder(this)
                .title("标题")
                .positiveText("确认")
                .items(arrays)
                .itemsCallbackSingleChoice(position, new MaterialDialog.ListCallbackSingleChoice() {
                    @Override
                    public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                        LogUtils.loge("选择的是什么>>>>" + which + text);
                        if (null == text) {
                            return true;
                        }
                        switch (flag) {
                            case 1:
                                //性别
                                if (text.equals("男")) {
                                    sex_p = "1";
                                    sex.setText("男");
                                } else {
                                    sex_p = "2";
                                    sex.setText("女");
                                }
                                break;
                            case 2:
                                //职业
                                job.setText(text);
                                break;
                            case 3:
                                //学历
                                education.setText(text);
                                break;
                        }
                        return true;
                    }
                })
                .show();
    }


    String avatar_url = "";//头像参数
    String region_id = "";//地区
    String sex_p = "";
    String hobby_ids = "";//爱好

    private void setUserInfo() {
        startProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("nickname", nickName.getText().toString());
//        map.put("phone", phone.getText().toString());
        if(!TextUtils.isEmpty(sex_p)){
            map.put("sex", sex_p);
        }
        map.put("wechat", wechatCode.getText().toString());
        map.put("region_id", region_id);
        map.put("edba", education.getText().toString());
//        map.put("age", age);
        map.put("height", height.getText().toString());
//        map.put("weight", weight.getText().toString());
        map.put("hobby_ids", hobby_ids);
        map.put("sign", sign.getText().toString());
        map.put("position", job.getText().toString());
        map.put("birthday", birthday.getText().toString());
        map.put("avatar", avatar_url);
        RetrofitManager.ApiFunc(RetrofitManager.mApiFunc.setUser(map), new SubscriberListener<BaseResponse<Object>>() {
            @Override
            public void onSuccess(BaseResponse<Object> objectBaseResponse) {
                stopProgressDialog();
//                ToastUtil.show(objectBaseResponse.getMsg());
                showCentToast(objectBaseResponse.getMsg());
                EventBus.getDefault().post(C.EVENT.UPDATE_USERINFO);
                finish();
            }

            @Override
            public void onFailer(String msg) {
                stopProgressDialog();
                showCentToast(msg);
            }

            @Override
            public void onTokenError() {

            }
        });
    }

    private void getUserInfo() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", App.getUid());
        map.put("page", "1");
        RetrofitManager.ApiFunc(RetrofitManager.mApiService.getUser(map), new SubscriberListener<BaseResponse<UserInfo>>() {
            @Override
            public void onSuccess(BaseResponse<UserInfo> listBaseResponse) {
                UserInfo userInfo = listBaseResponse.data;
                if (userInfo != null) {
                    avatar_url = userInfo.getAvatar();
                    GlideUtil.displayCircle(PersonDataActivity.this, avatar, userInfo.getAvatar());
                    nickName.setText(userInfo.getNickname());
                    region_id = String.valueOf(userInfo.getRegion_id());//地区
                    sex_p = userInfo.getSex();
                    hobby_ids = userInfo.getHobby_ids();//爱好
                    wechatCode.setText(userInfo.getWechat());
                    phone.setText(userInfo.getPhone());
                    birthday.setText(userInfo.getBirthday());

                    job.setText(userInfo.getPosition());
                    education.setText(userInfo.getEdba());
                    height.setText(userInfo.getHeight());
                    weight.setText(userInfo.getWeight());

                    hobby_ids = userInfo.getHobby_ids();
                    String[] hobbyString = hobby_ids.split(",");
                    for (int i=0;i<hobbyString.length;i++){
                        if(!TextUtils.isEmpty(hobbyString[i])){
                            hobbyList.add(hobbyString[i]);
                        }
                    }
                    tagAdapter.notifyDataChanged();

                    sign.setText(userInfo.getSign());

                    if ("1".equals(sex_p)) {
                        sex.setText("男");
                    } else if("2".equals(sex_p)){
                        sex.setText("女");
                    }

                    getUserRegion(userInfo.getRegion_id());
                }
            }

            @Override
            public void onFailer(String msg) {
            }

            @Override
            public void onTokenError() {
            }
        });
    }

    List<AddressData.ChildrenBean> childrens = new ArrayList<>();
    private void getUserRegion(final int addressId) {
        HttpUtils.ApiFunc(RetrofitManager.mApiFunc.getUserRegion(), new SubscriberListener<BaseResponse<List<AddressData>>>() {
            @Override
            public void onSuccess(BaseResponse<List<AddressData>> listBaseResponse) {
                final List<AddressData> addressDatas = listBaseResponse.getData();
                final int size = addressDatas.size();
                RxThreadUtils.asyncThread(new RxCallBack<String>() {
                    @Override
                    public String doSomeThing() {
                        for (int i = 0; i < size; i++) {
                            childrens.addAll(addressDatas.get(i).getChildren());
                        }
                        for (int i = 0; i < childrens.size(); i++) {
                            if(childrens.get(i).getValue()==addressId){
                                return childrens.get(i).getLabel();
                            }
                        }
                        return "请选择所在地区";
                    }

                    @Override
                    public void callBackUI(String label) {
                        address.setText(label);
                    }
                });
            }

            @Override
            public void onFailer(String msg) {

            }

            @Override
            public void onTokenError() {

            }
        });
    }
}
